<?php
/**
 * 用户模型
 * @author cnruhua
 */
require COMMON_PATH.'crypt.php';

class UserModel extends Model{

    protected $fields = array(
        'id','account', 'password','role', 'realname', 'email', 'created','status','logintime','loginip',
        '_pk'=>'id',
        '_autoInc'=>false
    );

    protected $_validate = array(
        array('role','require','{%dao_role_lost}'),
        array('account','/^[a-zA-Z][a-zA-Z0-9_@-]{0,15}$/','{%column_username}{%column_username_tip}'),
        array('password','/^.{6,}$/','{%column_password}{%column_password_tip}',2),
        array('realname','require','{%dao_realname_lost}')
    );

    protected $_auto = array(
        array('account','trim',Model::MODEL_BOTH,'function'),
        array('realname','trim',Model::MODEL_BOTH,'function'),
        array('password','cryptUserPassword',Model::MODEL_BOTH,'function')
    );

    /**
     * 用户登录验证
     */
    public function doLogin(){/*{{{*/
        $userid = $_POST['userid'];
        $pwd = $_POST['pwd'];
        if(empty($userid) || empty($pwd)){
            return false;
        }
        $rs = $this->where("account='{$userid}' and status>0")->find();
        if(!$rs || $rs['password'] !== cryptUserPassword($pwd) ){
            $this->error = L('login_fail');
            return false;
        }
        $roleRs = $this->field('name')->where("id={$rs['role']}")
                       ->table(C('db_prefix').'role')->find();
        if('0' == $roleRs['status']){
            $this->error = sprintf(L('role_forbidden'),$roleRs['name']);
            return false;
        }
        import('@.Util.RBAC');
        RBAC::saveAccessList($roleRs);
        $user_auth_key = C('user_auth_key');
        $_SESSION[$user_auth_key]['user'] = $rs;
        $_SESSION[$user_auth_key]['role'] = $roleRs;
        //登录事件
        if($lastLogin = LogModel::findLast($rs['id'],'LOGIN')){
            $_SESSION[$user_auth_key]['login'] = $lastLogin;
        }
        Load('extend');
        $update_data = array('logintime'=>datetime(),'loginip'=>get_client_ip());
        $this->where("id={$rs['id']}")->save($update_data);
        LogModel::log($rs['id'],'LOGIN',$update_data);
        return true;
    }/*}}}*/

    public function addUser(){/*{{{*/
        $vo = $this->create();
        if(!$vo) return false;
        if(!$this->checkRoleExist($vo['role'])){
            $this->error = L('dao_no_such_role');
            return false;
        }
        if($this->where("account='{$vo['account']}'")->find()){
            $this->error = sprintf(L('dao_account_used'),$vo['account']);
            return false;
        }
        $vo['created'] = datetime();
        $vo['status'] = '1';
        $this->startTrans();
        if($this->add($vo)){
            $this->commit();
            return $vo;
        }
        $this->rollback();
        $this->error = L('dao_add_user_fail');
        return false;
    }/*}}}*/

    public function updateUser(){
        $vo = $this->create();
        if(!$vo) return false;
        $userRs = $this->findUserById($vo['id']);
        if(false === $userRs){
            $this->error = L('module_no_such_user');
            return false;
        }
        $vo['account'] = $userRs['account'];
        if(!$this->checkRoleExist($vo['role'])){
            $this->error = L('dao_no_such_role');
            return false;
        }
        if(empty($_POST['password'])){
            $vo = array_diff_key($vo,array('password'=>'')); //dont't update password field
        }
        $this->startTrans();
        if(false!==$this->where("id={$vo['id']}")->save($vo)){
            $this->commit();
            return $vo;
        }
        $this->rollback();
        $this->error = L('module_update_user_fail');
        return false;
    }

    /**
     * 更新当前登录者的信息
     */
    public function updateMyself(){
        $user = $_SESSION[C('USER_AUTH_KEY')]['user'];
        $_POST = array_merge($user,$_POST);
        $vo=$this->create();
        if(!$vo){ return false;}

        if('pwd' !== $_POST['editype']){
            $vo['password'] = $user['password'];
        }else{
            //TODO 修改密码时要验证原密码
        }
        $this->startTrans();
        if($this->save($vo)){
            $this->commit();
            $_SESSION[C('USER_AUTH_KEY')]['user'] =  $vo;
            return true;
        }
        $this->rollback();
        return false;
    }

    private function checkRoleExist($roleId){
        return !(false===$this->query("select * from ".$this->tablePrefix."role where id={$roleId}"));
    }

    private function checkUserExistById($userId){
        return (false!==$this->where("id={$userId}")->find())?true:false;
    }

    private function findUserById($userId){
        return $this->where("id={$userId}")->find();
    }

}
